package com.ques.controller;

import com.alibaba.fastjson.JSON;
import com.ques.entity.QueryParam;
import com.ques.pojo.Question;
import com.ques.service.QuestionService;
import com.ques.utils.BasicMessage;
import com.ques.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author zq  2020-02-09
 */
@RestController
@RequestMapping("/api")
public class QuestionRestController {
    @Value("${server.port:8080}")
    private String port;
    @Value("${server.servlet.context-path:/}")
    private String path;
    @Value("${server.host:127.0.0.1}")
    private String host;

    private String logoPath = QuestionRestController.class.getResource("/").getPath() + "logo.png";

    @Autowired
    private QuestionService questionService;

    /**
     * 创建问卷
     *
     * @param question 问卷模板
     */
    @PostMapping("/createQuestion")
    public BasicMessage createQuestionnaire(@RequestBody Question question) {
        Question questionnaire = questionService.createQuestion(question);
        if (questionnaire == null) {
            return BasicMessage.fail().putmessage("error", "插入失败，请重新尝试！");
        } else {
            return BasicMessage.success().putmessage("data", JSON.toJSONString(question));
        }
    }

    @PostMapping("/deleteQuestion")
    public BasicMessage deleteQuestion(@RequestBody String[] questionIds) {
        long count =  questionService.deleteQuestion(questionIds);
        return BasicMessage.success().putmessage("count",count);

    }


    @PostMapping("/updateQuestion")
    public BasicMessage updateQuestion(@RequestBody Question question) {
        Question questionnaire = questionService.updateQuestion(question);
        if (questionnaire == null) {
            return BasicMessage.fail().putmessage("error", "插入失败，请重新尝试！");
        } else {
            return BasicMessage.success().putmessage("data", JSON.toJSONString(question));
        }
    }

    /**
     * 获取用户 的 所有 问卷
     *
     * @param userId 用户id号
     * @return
     */
    @PostMapping("/getAllQuestion")
    public BasicMessage getAllQuestion(@RequestBody QueryParam queryParam) {
        List<Question> allQuestion = questionService.getAllQuestion(queryParam);
        return BasicMessage.success().putmessage("message", allQuestion).putmessage("total", queryParam.getTotal());
    }

    /**
     * 修改问卷状态
     *
     * @param questionId 问卷id
     * @return
     */
    @PostMapping("/updateQuestionStatus")
    public BasicMessage updateQuestionStatus(String questionId, boolean status) {
        boolean flag = questionService.updateQuestionStatus(questionId, status);
        return BasicMessage.success();
    }

    @PostMapping("/getQuestion/{questionId}")
    public BasicMessage getQuestion(@PathVariable String questionId) {
        Question question = questionService.getQuestionById(questionId);
        System.out.println(JSON.toJSONString(question));
        return BasicMessage.success().putmessage("message", question);
    }

    @PostMapping("/downCode/{questionId}")
    public void downCode(@PathVariable String questionId, HttpServletResponse response) throws Exception {
        // 对id进行解析
        StringBuilder url = new StringBuilder(host);
        url.append(":");
        url.append(port);
        url.append("/");
        url.append(path);
        url.append("/");
        url.append(questionId);
        url.append(".html");
        response.setHeader("Content-Type", "application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + questionId + ".png");
        QRCodeUtil.encoderQRCode(url.toString(), response.getOutputStream(), logoPath, "png", 17);
    }
}
